const jwt = require("../config/jwt");
const client = require("../models");


module.exports = function(request,response,next){
    const allow = [
        '/','/api/admin/login','/api/admin/register' 
    ]
    let url = request.url
    // 允许通过的路由
    if(allow.includes(url)){
        next();
    }else{ 
        // 验证当前路由是否有token权限 
        let token = request.headers.access_token 
        if(!token){
            response.send({msg:"访问失败！请传递token",code:403})
        }else{ 
            // 验证token是否有效
            let user_id = jwt.getHeaderToken(request); 
            if(!user_id){ 
                response.send({msg:"访问失败！token无效",code:403})
            }else{
                // 验证user_id是否存在数据库中
                client.query("select * from user_msg where id = ? and isDelete = ?",[user_id,"0"],function(err,results){
                    if(!results || !results.length){
                        response.send({msg:"访问失败！token非法，已经禁止访问",code:403})
                    }else{ 
                        next();
                    }
                })
            }
        } 
    } 
}